import { ContextWithMiddleware } from './ContextWithMiddleware';

declare global {
  interface Window {
    __CONTEXT_DEVTOOLS__?: {
      getState: () => Record<string, unknown>;
      subscribe: (listener: () => void) => () => void;
      dispatch: (action: { type: string; payload?: unknown }) => void;
    };
  }
}

export class DevToolsContext extends ContextWithMiddleware {
  private devToolsListeners: Array<() => void> = [];

  constructor() {
    super();
    this.setupDevTools();
  }

  private setupDevTools(): void {
    if (
      typeof window !== 'undefined' &&
      process.env.NODE_ENV === 'development'
    ) {
      window.__CONTEXT_DEVTOOLS__ = {
        getState: () => ({ ...this.data }),
        subscribe: (listener) => {
          this.devToolsListeners.push(listener);
          return () => {
            this.devToolsListeners = this.devToolsListeners.filter(
              (l) => l !== listener,
            );
          };
        },
        dispatch: (action) => {
          console.log('DevTools Action:', action);
        },
      };
    }
  }

  protected notifyListeners(key: string, newValue: unknown): void {
    super.notifyListeners(key, newValue);
    this.notifyDevTools();
  }

  private notifyDevTools(): void {
    this.devToolsListeners.forEach((listener) => {
      try {
        listener();
      } catch (error) {
        console.error('DevTools listener error:', error);
      }
    });
  }
}
